import axios from 'axios'
import { useUserStore } from '@/store/modules/user'
import { Modal, message } from 'ant-design-vue'
import router from '@/router'

// getConfig();

// 不报错白名单(以error.response.data.message为参照)
const errWhite = ['未知错误!', '服务异常，没有找到服务的接口信息！', '权限不足,用户未登录!']

// 创建一个axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API_URL,
  timeout: 60000, // request timeout
})

// 请求拦截
service.interceptors.request.use(
  config => {
    const token = useUserStore().getToken()
    // 如果store存有token,则为每次请求附上token
    if (token) config.headers!.Token = token

    return config
  },
  error => {
    return Promise.reject(error)
  },
)

// 返回拦截
service.interceptors.response.use(
  response => {
    if ((response?.data as any)?.type === 'application/octet-stream') {
      let fileName = '未知文件.txt'

      if (response.headers['content-disposition'].split('=')[1].indexOf('json') > 0)
        fileName = decodeURI(response.headers['content-disposition'].split('=')[1])
      else
        fileName = decodeURI(
          response.headers['content-disposition'].split(';')[2].split('=')[1].split("UTF-8''")[1],
        )

      const URL = window.URL
      const objectUrl = URL.createObjectURL(response.data)
      if (fileName) {
        const a = document.createElement('a')
        if (typeof a.download === 'undefined') {
          window.location = objectUrl as unknown as Location
        } else {
          a.href = objectUrl
          a.download = fileName
          document.body.appendChild(a)
          a.click()
          a.remove()
        }
      } else {
        window.location = objectUrl as unknown as Location
      }
    }

    return response.data
  },
  error => {
    console.log(error)
    // if (error.response.status === 402) {
    //   if (router.currentRoute.value.path === '/' || router.currentRoute.value.path === '/login') {
    //     useUserStore().resetToken()
    //     location.reload()
    //   } else {
    //     Modal.confirm({
    //       content: '您的身份已过期，请选择重新登录，或留在此页。',
    //       okText: '重新登录',
    //       onOk() {
    //         useUserStore().resetToken()
    //         location.reload()
    //       },
    //     })
    //   }
    // }
    // 如果报错信息在报错白名单里则不报错
    if (!errWhite.includes(error.response.data.message)) {
      message.error(error.response.data.message, 5)
    }

    return Promise.reject(error)
  },
)

export default service
